import { _decorator, AudioClip, AudioSource, Component, director, DirectorEvent, Node } from 'cc';
import { PLAY_AUDIO } from './Event';
import { AUDIO_EFFECT_ENUM, GAME_EVENT_ENUM } from './Enum';
const { ccclass, property } = _decorator;

@ccclass('MusicManager')
export class MusicManager extends Component {

    @property(AudioClip)
    clickButton: AudioClip = null;
    @property(AudioClip)
    clickBlock: AudioClip = null;
    @property(AudioClip)
    clear: AudioClip = null;
    @property(AudioClip)
    lose: AudioClip = null;
    @property(AudioClip)
    win: AudioClip = null;
    @property(AudioClip)
    mainBgm: AudioClip = null;
    @property(AudioClip)
    gameBgm: AudioClip = null;
    @property(AudioSource)
    audioSource: AudioSource = null;

    protected onLoad(): void {
        director.addPersistRootNode(this.node); // 防止本节点被注销
        // 注册场景切换事件
        director.on(DirectorEvent.AFTER_SCENE_LAUNCH, this.onSceneLaunch, this);
        // 管理音效事件
        PLAY_AUDIO.on(GAME_EVENT_ENUM.PLAY_AUDIO, this.onAudioPlay, this);
    }

    onAudioPlay(type: AUDIO_EFFECT_ENUM) {
        switch (type) {
            case AUDIO_EFFECT_ENUM.CLICKBUTTON:
                this.audioSource.playOneShot(this.clickButton)
                break;
            case AUDIO_EFFECT_ENUM.CLEAR:
                this.audioSource.playOneShot(this.clear)
                break;
            case AUDIO_EFFECT_ENUM.CLICKCARD:
                this.audioSource.playOneShot(this.clickBlock)
                break;
            case AUDIO_EFFECT_ENUM.WIN:
                this.audioSource.playOneShot(this.win)
                break;
            case AUDIO_EFFECT_ENUM.LOSE:
                this.audioSource.playOneShot(this.lose)
                break;
            default:

        }
    }

    /**
     * 场景切换
     */
    onSceneLaunch() {
        let sceneName = director.getScene()?.name;
        this.updateBGMusic(sceneName)
    }

    updateBGMusic(sceneName: string) {
        switch (sceneName) {
            case 'Main':
                this.audioSource.stop()
                this.audioSource.clip = this.mainBgm;
                break;
            case 'Game':
                this.audioSource.stop()
                this.audioSource.clip = this.gameBgm;
                break;
        }

        if (this.audioSource.clip) {
            this.audioSource.play();
        }
    }

    update(deltaTime: number) {
        
    }

    protected onDestroy(): void {
        PLAY_AUDIO.off(GAME_EVENT_ENUM.PLAY_AUDIO, this.onAudioPlay, this);
        director.off(DirectorEvent.AFTER_SCENE_LAUNCH, this.onSceneLaunch, this);
    }
}

